package com.glory.gloryquickui.widget.datepicker;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.glory.gloryquickui.R;
import com.glory.gloryquickui.entity.DateBean;
import com.glory.gloryquickui.utils.DateUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class CustomDateRangePicker implements View.OnClickListener {

    public static final int RERSULT_CODE = 200;
    public static final String START = "START";
    public static final String END = "END";
    public static final String DAY_NUMBER = "DAY_NUMBER";
    /**
     * 级联滚动延迟时间
     */
    private static final long LINKAGE_DELAY_DEFAULT = 100L;
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    break;
                case 2:
                    break;
                default:
                    break;
            }
        }
    };
    private Context mContext;
    private Callback mCallback;
    private boolean mCanDialogShow;
    private Dialog mPickerDialog;
    private boolean mCanShowArea;
    private Thread thread;
    private String mSelectText;
    private List<String> mData = new ArrayList<>();
    private List<DateBean> mDtaeBeans;
    private List<DateBean.DayBean> mDayList;
    private int mType = -1;
    private RecyclerView mRecyclerView;
    private TextView mTvCancel;
    private TextView mTvTitle;
    private TextView mTvOk;
    private String mStartDate, mEndDate;

    /**
     * 通过时间戳初始换时间选择器，毫秒级别
     *
     * @param context  Activity Context
     * @param callback 选择结果回调
     */
    public CustomDateRangePicker(Context context, Callback callback, int higth) {
        if (context == null || callback == null) {
            mCanDialogShow = false;
            return;
        }
        mContext = context;
        mCallback = callback;
        initView(higth);
        initData();
        initRecyclerView();
        mCanDialogShow = true;
    }

    private void initView(int higth) {
        mPickerDialog = new Dialog(mContext, R.style.date_picker_dialog);
        mPickerDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mPickerDialog.setContentView(R.layout.dialog_date_range_picker);
        Window window = mPickerDialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.gravity = Gravity.BOTTOM;
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = higth;
            window.setAttributes(lp);
        }
        mRecyclerView = mPickerDialog.findViewById(R.id.rvDate);
        mTvCancel = mPickerDialog.findViewById(R.id.tv_cancel);
        mTvOk = mPickerDialog.findViewById(R.id.tv_confirm);
        mPickerDialog.findViewById(R.id.tv_cancel).setOnClickListener(this);
        mPickerDialog.findViewById(R.id.tv_confirm).setOnClickListener(this);
        mTvTitle = mPickerDialog.findViewById(R.id.tv_title);


    }

    private void initData() {
        mDtaeBeans = new ArrayList<>();
        Calendar c = Calendar.getInstance();

        c.add(Calendar.MONTH, 1);  // 得到下一个月
        int nextYear = c.get(Calendar.YEAR);
        int nextMonth = c.get(Calendar.MONTH) + 1;
        DateBean dateBean1 = new DateBean();
        dateBean1.setMonth(nextMonth);
        dateBean1.setYear(nextYear);
        mDtaeBeans.add(dateBean1);

        for (int i = 0; i < 36; i++) {
            c.add(Calendar.MONTH, -1);  // 得到下一个月
            int lastYear = c.get(Calendar.YEAR);
            int lastMonth = c.get(Calendar.MONTH) + 1;
            DateBean dateBean2 = new DateBean();
            dateBean2.setMonth(lastMonth);
            dateBean2.setYear(lastYear);
            mDtaeBeans.add(0,dateBean2);
        }
        handleData();
    }

    private void initRecyclerView() {
        final CustomMonthDateRangeAdapter adapter = new CustomMonthDateRangeAdapter(mContext, mDtaeBeans);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter.setListener(new CustomMonthDateRangeAdapter.onDateSelectListener() {
            @Override
            public void onSelect(String date, int type) {
                mType = type;
                if (type == 0) {
                    mEndDate = date;
                    if (mEndDate.equals(mStartDate)) {
                        mCallback.onSexSelected(mStartDate, mEndDate);
                        if (mPickerDialog != null && mPickerDialog.isShowing()) {
                            mPickerDialog.dismiss();
                        }
                    } else {
                        mTvTitle.setText("选择完成");
                    }
                } else {
                    mStartDate = date;
                    mTvTitle.setText("请选择结束时间");
                }
            }
        });
        mRecyclerView.scrollToPosition(mDtaeBeans.size()-2);
    }

    private void handleData() {
        for (int i = 0; i < mDtaeBeans.size(); i++) {
            mDayList = new ArrayList<>();
            DateBean entity = mDtaeBeans.get(i);
            int month = entity.getMonth();
            int year = entity.getYear();
            Calendar calendar = Calendar.getInstance();
            calendar.set(year, month - 1, 1);  // 设置这个月的第一天
            int currYear = calendar.get(Calendar.YEAR);
            int currMonth = calendar.get(Calendar.MONTH);
            int day_of_week = calendar.get(Calendar.DAY_OF_WEEK); // 获取当前这天的星期
            // 获取第一天的前面空了几个星期
            int offset = day_of_week - 1;
//            // 获取当月最后一天
            int totalDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);  // 获取当月的天数
            for (int i1 = 0; i1 < offset; i1++) {
                String jr = DateUtils.getJR(0, 0);
                mDayList.add(new DateBean.DayBean(0, 0, 0, jr, false, false));
            }
            for (int i1 = 0; i1 < totalDays; i1++) {
                String jr = DateUtils.getJR(currMonth + 1, i1 + 1);
                mDayList.add(new DateBean.DayBean(currYear, currMonth + 1, (i1 + 1), jr, false, false));
            }
            mDtaeBeans.get(i).setDayBeans(mDayList);
        }
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_confirm) {
            if (mCallback != null) {
                if (mType == 0) {
                    mCallback.onSexSelected(mStartDate, mEndDate);
                    if (mPickerDialog != null && mPickerDialog.isShowing()) {
                        mPickerDialog.dismiss();
                    }
                } else {
                    Toast.makeText(mContext, "请先选择日期！", Toast.LENGTH_SHORT).show();
                }

            }
        } else if (id == R.id.tv_cancel) {
            mPickerDialog.dismiss();
        }

    }

    /**
     * 展示文本选择器
     */
    public void show(int position) {
        if (!canShow()) return;
        if (setSelectedSex(position, false)) {
            mPickerDialog.show();
        }
    }

    private boolean canShow() {
        return mCanDialogShow && mPickerDialog != null;
    }

    /**
     * @param showAnim 是否展示动画
     * @return 是否设置成功
     */
    public boolean setSelectedSex(int posittion, boolean showAnim) {
        if (!canShow()) return false;
        mSelectText = mData.get(posittion);

        return true;
    }

    /**
     * 默认显示第一条数据
     */
    public void show() {
        if (!canShow()) return;
        mPickerDialog.show();
    }

    /**
     * 设置是否允许点击屏幕或物理返回键关闭
     */
    public void setCancelable(boolean cancelable) {
        if (!canShow()) return;
        mPickerDialog.setCancelable(cancelable);
    }

    /**
     * 设置日期控件是否可以循环滚动
     */
    public void setScrollLoop(boolean canLoop) {
        if (!canShow()) return;

    }

    /**
     * 设置日期控件是否展示滚动动画
     */
    public void setCanShowAnim(boolean canShowAnim) {
        if (!canShow()) return;

    }

    /**
     * 销毁弹窗
     */
    public void onDestroy() {
        if (mPickerDialog != null) {
            mPickerDialog.dismiss();
            mPickerDialog = null;

        }
    }

    /**
     * 时间选择结果回调接口
     */
    public interface Callback {
        void onSexSelected(String startDate, String endDate);
    }

}
